package com.mysql.opt.controller;

import com.alibaba.excel.EasyExcel;
import com.mysql.opt.entity.OrderInfo;
import com.mysql.opt.entity.OrderInfoModel;
import com.mysql.opt.service.OrderInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
public class OrderInfoController {

    @Resource
    private OrderInfoService orderInfoService;
    
    @PostMapping("/order/export")
    public void exportOrder(@RequestBody OrderInfo orderInfo, HttpServletResponse servletResponse) throws IOException {
        List<OrderInfo> result = orderInfoService.export(orderInfo);
        List<OrderInfoModel> exportList = new ArrayList<>(result.size());
        for (OrderInfo info : result) {
            OrderInfoModel orderInfoModel = new OrderInfoModel();
            BeanUtils.copyProperties(info, orderInfoModel);
            exportList.add(orderInfoModel);
        }

        servletResponse.setContentType("application/vnd.ms-excel");
        servletResponse.setCharacterEncoding("utf-8");
        // 保证下载到本地文件名不乱码的
        String fileName = URLEncoder.encode("模版", "UTF-8");
        servletResponse.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        // List<模型> 的数据体，替换成自己的业务代码即可
        EasyExcel.write(servletResponse.getOutputStream(), OrderInfoModel.class).sheet("sheet").doWrite(exportList);
    }
}
